package game.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import common.mapper.CommonGLandformMapper;
import common.model.po.GBuildingLandform;
import common.model.po.GLandform;
import common.model.request.base.PaginationRequest;
import common.model.response.base.Result;
import common.service.CommonGBuildingLandformService;
import game.model.converter.GLandformConverter;
import game.model.request.SaveLandformRequest;
import game.model.request.SearchLandformRequest;
import game.service.GLandformService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 地貌服务实现类
 *
 * @author 米泽鹏
 * @since 2022-02-26
 */
@Service
public class GLandformServiceImpl extends ServiceImpl<CommonGLandformMapper, GLandform> implements GLandformService {

	@Resource
	private CommonGLandformMapper mapper;
	@Resource
	private CommonGBuildingLandformService buildingLandformService;

	@Override
	public Page<GLandform> searchLandformByPage(PaginationRequest<SearchLandformRequest, GLandform> paginationRequest) {
		LambdaQueryWrapper<GLandform> queryWrapper = paginationRequest.buildQueryWrapper().lambda();
		queryWrapper.orderByAsc(GLandform::getId);
		return page(paginationRequest.buildPage(), queryWrapper);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Result<?> saveLandform(SaveLandformRequest request) {
		GLandform gLandform = GLandformConverter.requestToPo(request);
		if (gLandform.getId() == null) {
			save(gLandform);
		} else {
			// 地貌名称修改后需要连带修改g_building_landform表的landform_name字段
			GLandform gLandformOriginal = getById(gLandform.getId());
			if (!gLandformOriginal.getLandformName().equals(gLandform.getLandformName())) {
				buildingLandformService.lambdaUpdate().eq(GBuildingLandform::getLandformId, gLandform.getId()).set(GBuildingLandform::getLandformName, gLandform.getLandformName()).update();
			}
			updateById(gLandform);
		}
		return Result.success();
	}

}
